import { createRouter, createWebHistory } from 'vue-router'

import AppLayout from '@/layout/AppLayout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登录',
        hidden: true,
      },
    },
    {
      path: '/',
      component: AppLayout,
      redirect: '/home',
      children: [
        { path: 'home', component: () => import('@/views/index.vue') },
        {
          path: '/docs/view/:id',
          component: () => import('@/views/editor/index.vue'),
        },
        { path: 'profile', component: () => import('@/views/userInfo/index.vue') },
      ],
    },
  ],
})

router.beforeEach((to, from, next) => {
  // Set the document title
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '文档编辑器'
  }

  // Check if the user is logged in
  const isLoggedIn = localStorage.getItem('token') !== null

  // Redirect to login page if not logged in and trying to access a protected route
  if (!isLoggedIn && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
